package ru.artyushov.fingers.core.filter;

/**
 * User: nikart
 * Date: 09.05.12
 */

import ru.artyushov.fingers.core.SpecialPointsFilter;
import ru.artyushov.fingers.core.data.Fingerprint;
import ru.artyushov.fingers.core.data.Point;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * removes dead ends that are located on the edge of the fingerprint
 */
public class EdgeDeadEndsFilter implements SpecialPointsFilter {

    @Override
    public List<Point> filter(Fingerprint fingerprint, Collection<Point> points) {

        List<Point> result = new ArrayList<Point>();

        for (final Point point : points) {
            boolean isEdgePoint = false;
            for (int dx = -1; dx <= 1; dx += 2) {
                for (int dy = -1; dy <= 1; dy += 2) {
                    isEdgePoint |= isEmpty(getSubmatrix(fingerprint.getData(), point.x, point.y, dx, dy));
                }
            }
            if (!isEdgePoint) {
                result.add(point);
            }
        }

        return result;
    }

    private boolean[][] getSubmatrix(boolean[][] data, int col, int row, int dx, int dy) {
        int width;
        if (dx < 0) {
            width = col - 1;
        } else {
            width = data.length - col - 1;
        }
        int height;
        if (dy < 0) {
            height = row - 1;
        } else {
            height = data[0].length - row - 1;
        }
        boolean[][] result = new boolean[width][height];
        for (int i = 0; i < width; i ++) {
            for (int j = 0; j < height; j ++) {
                result[i][j] = data[col + i * dx + dx][row + j * dy + dy];
            }
        }
        return result;
    }

    private boolean isEmpty(boolean[][] data) {
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                if (data[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }
}
